package com.zjitc.service.impl;

import com.zjitc.common.ServerResponse;
import com.zjitc.dao.ProductDao;
import com.zjitc.dao.UserDao;
import com.zjitc.model.Comment;
import com.zjitc.model.Pay;
import com.zjitc.model.Product;
import com.zjitc.model.ProductVo;
import com.zjitc.model.User;
import com.zjitc.service.ProductService;
import com.zjitc.service.UserService;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Create by IntelliJ IDEA
 *
 * @author: jsonor
 * @date-Time: 2018/5/2 16:53
 * @description:
 */
@Service
public class ProductServiceImpl implements ProductService {

  @Autowired
  private ProductDao productDao;

  @Autowired
  private UserDao userDao;

  @Override
  public ServerResponse<Product> pushProduct(Product product) {
    if (product.getName() == null) {
      return ServerResponse.createError("商品已经存在");
    }
    int count = productDao.checkName(product.getName());
    if (count == 1) {
      return ServerResponse.createError("商品已经存在");
    }

    int integer = productDao.pushProduct(product);
    return ServerResponse.createSucess(product);
  }

  @Override
  public List<Product> productAll() {
    return productDao.productAll();
  }

  @Override
  public Product showProduct(Integer id) {
    Product product = productDao.showProduct(id);
    return product;
  }


  @Override
  public void delete(Integer id) {
    productDao.delete(id);
  }

  @Override
  public List<ProductVo> showComment() {

    List<Product> products = productDao.productAll();
    List<ProductVo> productVoList = new ArrayList<>();
    for (Product product : products) {
      ProductVo productVo = new ProductVo();
      List<Comment> comments = productDao.showComment(product.getId());
      for (Comment comment:comments){
        User user= userDao.findUserById(comment.getId());
        comment.setUser(user);
      }
      productVo.setPid(product.getId());
      productVo.setName(product.getName());
      productVo.setImage(product.getImage());
      productVo.setDescribe(product.getDescribe());
      productVo.setComment(comments);
      productVoList.add(productVo);
    }
    return productVoList;
  }

  @Override
  public void comment(String com,Integer pid,Integer id) {
    productDao.comment(com,pid,id);
  }

  @Override
  public Product pay(Integer money) {
    Product product = productDao.showProduct(money);
    return product;
  }

  @Override
  public String creatUid() {
    return UUID.randomUUID().toString();
  }

  @Override
  public void payAdd(String money, String username, String imageName) {
    productDao.payAdd(money,username,imageName);
  }


}
